import { request } from '@/utils/request'
import { calculateProjectProgress } from '@/utils/projectProgress'
import { ResponseParser } from '@/utils/responseParser'
import type { ApiResponse } from '@/types/api'

// 版本缺陷分布数据结构
export interface VersionDefectDistribution {
  version: string
  total_defects: number
  open_defects: number
  resolved_defects: number
  closed_defects: number
}

// 后端返回的仪表盘概览数据结构
export interface DashboardOverviewResponse {
  project_stats: {
    total_projects: number
    active_projects: number
    completed_projects: number
  }
  task_stats: {
    total_tasks: number
    pending_tasks: number
    in_progress_tasks: number
    completed_tasks: number
  }
  my_task_stats: {
    total_tasks: number
    pending_tasks: number
    in_progress_tasks: number
    completed_tasks: number
  }
  defect_stats: {
    total_defects: number
    open_defects: number
    resolved_defects: number
    closed_defects: number
  }
  requirement_stats: {
    total_requirements: number
    planning_requirements: number
    active_requirements: number
    completed_requirements: number
    on_hold_requirements: number
    cancelled_requirements: number
  }
  version_stats: {
    total_versions: number
    active_versions: number
    version_defect_distribution: VersionDefectDistribution[]
  }
  user_stats: {
    total_users: number
    active_users: number
    inactive_users: number
  }
  member_stats: {
    total_members: number
  }
}

// 前端使用的仪表盘统计数据接口（转换后）
export interface DashboardStats {
  totalProjects: number
  totalTasks: number
  totalUsers: number
  completionRate: number
  activeProjects: number
  completedProjects: number
  pendingTasks: number
  completedTasks: number
  inProgressTasks: number
  myTotalTasks: number
  myPendingTasks: number
  myInProgressTasks: number
  myCompletedTasks: number
  totalDefects: number
  openDefects: number
  resolvedDefects: number
  closedDefects: number
  totalRequirements: number
  planningRequirements: number
  activeRequirements: number
  completedRequirements: number
  onHoldRequirements: number
  cancelledRequirements: number
  totalVersions: number
  activeVersions: number
  versionDefectDistribution: VersionDefectDistribution[]
  totalMembers: number
}

// 任务进度趋势数据
export interface TaskProgressData {
  date: string
  created_count: number
  completed_count: number
}

// 最近活动数据
export interface RecentActivity {
  id: string
  type: 'task' | 'defect'
  title: string
  status: string
  project_id?: string
  assignee_id?: string
  created_at: string
  updated_at: string
}

// 获取仪表盘概览数据
export const getDashboardOverview = async (projectId?: string): Promise<DashboardOverviewResponse> => {
  const response = await request.get<ApiResponse<DashboardOverviewResponse>>('/dashboard/overview', {
    params: projectId ? { project_id: projectId } : {}
  })
  // 使用ResponseParser统一处理响应格式
  const parsed = ResponseParser.parseResponse<DashboardOverviewResponse>(response)
  if (parsed.success && parsed.data) {
    return parsed.data
  }
  throw new Error(parsed.message || '获取仪表盘数据失败')
}

// 获取最近活动
export const getRecentActivities = async (limit: number = 20, projectId?: string): Promise<RecentActivity[]> => {
  const response = await request.get<ApiResponse<RecentActivity[]>>('/dashboard/recent-activities', {
    params: {
      limit,
      ...(projectId && { project_id: projectId })
    }
  })
  // 使用ResponseParser统一处理响应格式
  const parsed = ResponseParser.parseResponse<RecentActivity[]>(response)
  if (parsed.success && parsed.data) {
    return parsed.data
  }
  throw new Error(parsed.message || '获取最近活动失败')
}

// 获取任务进度趋势
export const getTaskProgress = async (projectId?: string, days: number = 30): Promise<TaskProgressData[]> => {
  const response = await request.get<ApiResponse<TaskProgressData[]>>('/dashboard/task-progress', {
    params: {
      days,
      ...(projectId && { project_id: projectId })
    }
  })
  // 使用ResponseParser统一处理响应格式
  const parsed = ResponseParser.parseResponse<TaskProgressData[]>(response)
  if (parsed.success && parsed.data) {
    return parsed.data
  }
  throw new Error(parsed.message || '获取任务进度失败')
}

// 工作负载分布数据
export interface WorkloadDistribution {
  user_id: string
  username: string
  name: string
  email: string
  total_tasks: number
  pending_tasks: number
  in_progress_tasks: number
  completed_tasks: number
  total_estimated_hours: number
  total_actual_hours: number
}

// 项目健康度数据
export interface ProjectHealth {
  project_id: string
  project_name: string
  project_status: string
  total_tasks: number
  completed_tasks: number
  overdue_tasks: number
  total_defects: number
  open_defects: number
  task_completion_rate: number
  overdue_rate: number
  defect_rate: number
  project_progress: number
  health_score: number
  health_level: 'excellent' | 'good' | 'warning' | 'critical'
}

// 个人仪表盘数据
export interface MyDashboardData {
  my_tasks: {
    total: number
    todo: number
    in_progress: number
    done: number
    overdue: number
  }
  my_defects: {
    assigned: number
    reported: number
    open: number
  }
  my_requirements: {
    total: number
    pending: number
    in_progress: number
    completed: number
    cancelled: number
  }
  my_projects: Array<{
    id: string
    name: string
    status: string
  }>
  recent_tasks: Array<{
    id: string
    title: string
    status: string
    priority: string
    due_date?: string
    project_id?: string
  }>
  upcoming_tasks: Array<{
    id: string
    title: string
    due_date?: string
    priority: string
    project_id?: string
  }>
}

// 获取工作负载分布
export const getWorkloadDistribution = async (projectId?: string): Promise<WorkloadDistribution[]> => {
  const response = await request.get<ApiResponse<WorkloadDistribution[]>>('/dashboard/workload-distribution', {
    params: projectId ? { project_id: projectId } : {}
  })
  // 使用ResponseParser统一处理响应格式
  const parsed = ResponseParser.parseResponse<WorkloadDistribution[]>(response)
  if (parsed.success && parsed.data) {
    return parsed.data
  }
  throw new Error(parsed.message || '获取工作负载分布失败')
}

// 获取项目健康度
export const getProjectHealth = async (projectId?: string): Promise<ProjectHealth[]> => {
  const response = await request.get<ApiResponse<ProjectHealth[]>>('/dashboard/project-health', {
    params: projectId ? { project_id: projectId } : {}
  })
  // 使用ResponseParser统一处理响应格式
  const parsed = ResponseParser.parseResponse<ProjectHealth[]>(response)
  if (parsed.success && parsed.data) {
    return parsed.data
  }
  throw new Error(parsed.message || '获取项目健康度失败')
}

// 获取个人仪表盘数据
export const getMyDashboard = async (): Promise<MyDashboardData> => {
  const response = await request.get<ApiResponse<MyDashboardData>>('/dashboard/my-dashboard')
  // 使用ResponseParser统一处理响应格式
  const parsed = ResponseParser.parseResponse<MyDashboardData>(response)
  if (parsed.success && parsed.data) {
    return parsed.data
  }
  throw new Error(parsed.message || '获取个人仪表盘数据失败')
}

// 项目统计数据接口
export interface ProjectStats {
  total_projects: number
  active_projects: number
  completed_projects: number
  total_tasks: number
  completed_tasks: number
  total_defects: number
  resolved_defects: number
  total_requirements: number
  completed_requirements: number
}

// 团队效率数据接口
export interface TeamEfficiency {
  date: string
  completed_tasks: number
  created_tasks: number
  task_completion_rate: number
  average_completion_time: number
}

// 获取项目统计数据
export const getProjectStats = async (projectId?: string): Promise<ProjectStats> => {
  const response = await request.get<ApiResponse<ProjectStats>>('/dashboard/project-stats', {
    params: projectId ? { project_id: projectId } : {}
  })
  // 使用ResponseParser统一处理响应格式
  const parsed = ResponseParser.parseResponse<ProjectStats>(response)
  if (parsed.success && parsed.data) {
    return parsed.data
  }
  throw new Error(parsed.message || '获取项目统计数据失败')
}

// 获取团队效率数据
export const getTeamEfficiency = async (projectId?: string, days: number = 30): Promise<TeamEfficiency[]> => {
  const response = await request.get<ApiResponse<TeamEfficiency[]>>('/dashboard/team-efficiency', {
    params: {
      days,
      ...(projectId && { project_id: projectId })
    }
  })
  // 使用ResponseParser统一处理响应格式
  const parsed = ResponseParser.parseListResponse<TeamEfficiency>(response)
  if (parsed.success && parsed.data) {
    return parsed.data
  }
  throw new Error(parsed.message || '获取团队效率数据失败')
}

// 数据转换函数：将后端数据转换为前端使用的格式
export const transformDashboardData = (data: DashboardOverviewResponse): DashboardStats => {
  const { project_stats, task_stats, my_task_stats, defect_stats, requirement_stats, version_stats, user_stats, member_stats } = data
  
  // 计算完成率 - 使用与项目进度计算一致的逻辑
  const completionRate = calculateProjectProgress({
    requirement_count: requirement_stats.total_requirements,
    requirement_completed_count: requirement_stats.completed_requirements,
    task_count: task_stats.total_tasks,
    completed_task_count: task_stats.completed_tasks,
    defect_count: defect_stats.total_defects,
    resolved_defect_count: defect_stats.resolved_defects,
    test_case_count: 0, // 仪表盘没有测试用例数据
    passed_test_case_count: 0,
    project_status: undefined,
    start_date: undefined,
    end_date: undefined,
    progress: undefined
  })

  return {
    totalProjects: project_stats.total_projects,
    totalTasks: task_stats.total_tasks,
    totalUsers: user_stats?.total_users || 0,
    completionRate,
    activeProjects: project_stats.active_projects,
    completedProjects: project_stats.completed_projects,
    pendingTasks: task_stats.pending_tasks,
    completedTasks: task_stats.completed_tasks,
    inProgressTasks: task_stats.in_progress_tasks,
    myTotalTasks: my_task_stats.total_tasks,
    myPendingTasks: my_task_stats.pending_tasks,
    myInProgressTasks: my_task_stats.in_progress_tasks,
    myCompletedTasks: my_task_stats.completed_tasks,
    totalDefects: defect_stats.total_defects,
    openDefects: defect_stats.open_defects,
    resolvedDefects: defect_stats.resolved_defects,
    closedDefects: defect_stats.closed_defects,
    totalRequirements: requirement_stats.total_requirements,
    planningRequirements: requirement_stats.planning_requirements,
    activeRequirements: requirement_stats.active_requirements,
    completedRequirements: requirement_stats.completed_requirements,
    onHoldRequirements: requirement_stats.on_hold_requirements,
    cancelledRequirements: requirement_stats.cancelled_requirements,
    totalVersions: version_stats.total_versions,
    activeVersions: version_stats.active_versions,
    versionDefectDistribution: version_stats.version_defect_distribution,
    totalMembers: member_stats?.total_members || 0
  }
}